package com.ruoyi.web.controller.consumerAdmin;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.consumer.controller.facilit.api.APIService;
import com.ruoyi.consumer.controller.facilit.fill.FiaciltMode;
import com.ruoyi.consumer.controller.facilit.fill.FiaciltParameter;
import com.ruoyi.consumer.domain.CFillingFacilit;
import com.ruoyi.consumer.domain.CFillingStation;
import com.ruoyi.consumer.domain.CUnitPrice;
import com.ruoyi.consumer.domain.FUser;
import com.ruoyi.consumer.service.impl.CFillingFacilitServiceImpl;
import com.ruoyi.consumer.service.impl.CFillingStationServiceImpl;
import com.ruoyi.consumer.service.impl.CUnitPriceServiceImpl;
import com.ruoyi.consumer.service.impl.FUserServiceImpl;
import com.ruoyi.consumer.utils.MapApiRequest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author: lizhouwei
 * @ date : 2023/11/14
 * @description:
 */
@Api(tags = "加注站,加注机管理")
@RestController
@RequestMapping("/api/station")
public class StationController {

    @Autowired
    private CFillingStationServiceImpl fillingStationService;

    @Autowired
    private FUserServiceImpl fUserService;

    @Autowired
    private CFillingFacilitServiceImpl fillingFacilitService;

    @Autowired
    private APIService apiService;

    @Autowired
    private CUnitPriceServiceImpl unitPriceService;

    @Autowired
    private RedisCache redisCache;

    //查询加注员是否绑定加注站
    @ApiOperation("查询加注员是否绑定加注站")
    @GetMapping("/is-bind-station")
    public AjaxResult isBindStation(@RequestParam("userId") Integer userId) {
        CFillingStation cFillingStation = new CFillingStation();
        cFillingStation.setFillerId(userId);
        List<CFillingStation> cFillingStations = fillingStationService.selectCFillingStationList(cFillingStation);
        if (cFillingStations.isEmpty()) {
            return AjaxResult.success("没有绑定");
        }
        return AjaxResult.success("已绑定加注站");
    }

    //设置FUser用户为加注员
    @ApiOperation("查询加注员是否绑定加注站")
    @GetMapping("/setFuser")
    public AjaxResult setFuser(@RequestParam("userId") Integer userId) {
        FUser fUser = fUserService.selectFUserByUserId(userId);
        if (fUser == null) {
            return AjaxResult.error("用户不存在");
        }
        if (fUser.getIsDelete() == 1) {
            return AjaxResult.error("已经是加注员");
        }
        fUser.setIsDelete(1);
        fUserService.updateFUser(fUser);
        return AjaxResult.success("设置成功");
    }

    //查看未添加的加注机
    @ApiOperation("查看未添加的加注机")
    @GetMapping("/selectCFillingFacilitList")
    public AjaxResult selectCFillingFacilitList() {
        CFillingFacilit cFillingFacilit = new CFillingFacilit();
        cFillingFacilit.setStatus(3);
        List<CFillingFacilit> cFillingFacilitList = fillingFacilitService.selectCFillingFacilitList(cFillingFacilit);
        return AjaxResult.success(cFillingFacilitList);
    }

    //绑定加注机
    @ApiOperation("绑定加注机")
    @GetMapping("/bindFacilit")
    public AjaxResult bindFacilit(@RequestParam("stationId") Integer stationId,
                                  @RequestParam("facilitId") Integer facilitId) throws Exception {
        CFillingFacilit cFillingFacilit = fillingFacilitService.selectCFillingFacilitByFacilitId(facilitId);
        if (cFillingFacilit == null) {
            return AjaxResult.error("加注机不存在");
        }
        if (cFillingFacilit.getStatus() != 3) {
            return AjaxResult.error("加注机已被绑定");
        }
        String equipmentInfoBySn = apiService.getEquipmentInfoBySn(cFillingFacilit.getFacilitSn(), redisCache.getCacheObject("token:" + "authorizerAccessToken"));
        System.out.println("获取加注机状态返回值:" + equipmentInfoBySn);
        //设置设备库位信息
        String equipmentStockBySn = apiService.getEquipmentStockBySn(cFillingFacilit.getFacilitSn(), redisCache.getCacheObject("token:" + "authorizerAccessToken"));
        System.out.println("获取加注机库存返回值:" + equipmentStockBySn);
        Map<String, Object> manage = null;
        Map<String, Object> heartbeat = null;
        Map<String, Object> stock = null;
        try {
            String jsonString = equipmentInfoBySn; // 您的 JSON 字符串
            String stockJsonString = equipmentStockBySn; // 您的 JSON 字符串

            ObjectMapper mapper = new ObjectMapper();
            ObjectMapper stockmapper = new ObjectMapper();

            // 解析 JSON 字符串为 Map
            Map<String, Object> jsonMap = mapper.readValue(jsonString, Map.class);
            Map<String, Object> stockJsonMap = stockmapper.readValue(stockJsonString, Map.class);

            // 获取 datas 对象
            Map<String, Object> datas = (Map<String, Object>) jsonMap.get("datas");
            Map<String, Object> stockDatas = (Map<String, Object>) stockJsonMap.get("datas");

            // 获取 manage 对象
            if (datas != null) {
                manage = (Map<String, Object>) datas.get("manage");
                heartbeat = (Map<String, Object>) datas.get("heartbeat");
            }
            if (stockDatas != null) {
                stock = stockDatas;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("stock:" + stock);
        //将stock.get("stockAllowance")乘以1000后转换为Long类型
        Double allowanceDouble = (Double) stock.get("stockAllowance");
        Double totalDouble = (Double) stock.get("stockCapacity");
        Long allowanceLong = (long) (allowanceDouble * 1000);
        Long totalLong = (long) (totalDouble * 1000);
        //设置加机库位
        cFillingFacilit.setRemainingLiquid(allowanceLong);
        cFillingFacilit.setTotalLiquid(totalLong);


        //根据经纬度返回省市区
        cFillingFacilit.setFacilitLng((Double) manage.get("longitude"));
        cFillingFacilit.setFacilitLat((Double) manage.get("latitude"));

        StringBuilder sb = new StringBuilder();
        sb.append(cFillingFacilit.getFacilitLat());
        sb.append(",");
        sb.append(cFillingFacilit.getFacilitLng());
        Map<String, Object> addressMap = (Map<String, Object>) MapApiRequest.getAddress(sb.toString());
        cFillingFacilit.setFacilitProvince(addressMap.get("province").toString());
        cFillingFacilit.setFacilitCity(addressMap.get("city").toString());
        cFillingFacilit.setFacilitArea(addressMap.get("district").toString());

        //获取此时机器的运行模式
        if (heartbeat.get("equipmentMachineMode").equals("1")) {
            cFillingFacilit.setFacilitPattern(1);
        } else if (heartbeat.get("equipmentMachineMode").equals("2")) {
            cFillingFacilit.setFacilitPattern(2);
        }

        //设置默认临时加注单价
        List<CUnitPrice> cUnitPrices = unitPriceService.selectCUnitPriceList(new CUnitPrice());
        Integer unitTemporary = cUnitPrices.get(0).getUnitTemporary();
        double v = unitTemporary.doubleValue() / 100;
        cFillingFacilit.setFaciltKvs(155);
        cFillingFacilit.setUnitTemporary(unitTemporary);
        cFillingFacilit.setStatus(1);
        cFillingFacilit.setStationId(stationId);
        int i = fillingFacilitService.updateCFillingFacilit(cFillingFacilit);

        //调用设备信息修改接口
        FiaciltParameter fiaciltParameter = new FiaciltParameter();
        fiaciltParameter.setPrice(v);
        fiaciltParameter.setSn(cFillingFacilit.getFacilitSn());
        fiaciltParameter.setKvs(cFillingFacilit.getFaciltKvs());
        fiaciltParameter.setStates(cFillingFacilit.getStatus().toString());

        String s = apiService.setFaciltStatus(fiaciltParameter, redisCache.getCacheObject("token:" + "authorizerAccessToken"));

        //获取s倒数3,4个字符
        String substring = s.substring(s.length() - 4, s.length() - 2);
        System.out.println("修改加注机状态返回值:" + substring);
        if (substring.equals("成功") && i > 0) {
            return AjaxResult.success("绑定成功");
        } else if (!substring.equals("成功") || i == 0) {
            return AjaxResult.error("加注机不处于待机状态,无法绑定,请重试");
        }

        return AjaxResult.success("绑定成功");
    }

    //修改加注机参数
    @ApiOperation("修改加注机参数")
    @PostMapping("/updateStationStatus")
    public AjaxResult updateStationStatus(@RequestBody CFillingFacilit cFillingFacilit) throws Exception {
        if (cFillingFacilit == null) {
            return AjaxResult.error("加注机不存在");
        }

        String equipmentInfoBySn = apiService.getEquipmentInfoBySn(cFillingFacilit.getFacilitSn(), redisCache.getCacheObject("token:" + "authorizerAccessToken"));
        //解析{"datas":null,"resp_code":1,"resp_msg":"未查询到结果"}

        System.out.println("修改加注机状态返回值:" + equipmentInfoBySn);
        Map<String, Object> manage = null;
        Map<String, Object> heartbeat = null;
        try {
            String jsonString = equipmentInfoBySn; // 您的 JSON 字符串

            ObjectMapper mapper = new ObjectMapper();

            // 解析 JSON 字符串为 Map
            Map<String, Object> jsonMap = mapper.readValue(jsonString, Map.class);

            // 获取 datas 对象
            Map<String, Object> datas = (Map<String, Object>) jsonMap.get("datas");

            // 获取 manage 对象
            if (datas != null) {
                manage = (Map<String, Object>) datas.get("manage");
                heartbeat = (Map<String, Object>) datas.get("heartbeat");
            } else {
                return AjaxResult.error("未查询到该设备信息");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //根据经纬度返回省市区
        cFillingFacilit.setFacilitLng((Double) manage.get("longitude"));
        cFillingFacilit.setFacilitLat((Double) manage.get("latitude"));

        StringBuilder sb = new StringBuilder();
        sb.append(cFillingFacilit.getFacilitLat());
        sb.append(",");
        sb.append(cFillingFacilit.getFacilitLng());
        Map<String, Object> addressMap = (Map<String, Object>) MapApiRequest.getAddress(sb.toString());
        System.out.println("addressMap:" + addressMap);
        cFillingFacilit.setFacilitProvince(addressMap.get("province").toString());
        cFillingFacilit.setFacilitCity(addressMap.get("city").toString());
        cFillingFacilit.setFacilitArea(addressMap.get("district").toString());

        //修改加注机基本信息
        fillingFacilitService.updateCFillingFacilit(cFillingFacilit);

        //判断加注机是否处于待机状态
        if (!heartbeat.get("equipmentMachineState").toString().equals("1")) {
            return AjaxResult.error("加注机不处于待机状态,无法修改,请重试");
        }


        //获取临时加注单价
        Integer unitTemporary = cFillingFacilit.getUnitTemporary();
        double v = unitTemporary.doubleValue() / 100;


        //调用设备信息修改接口
        FiaciltParameter fiaciltParameter = new FiaciltParameter();
        fiaciltParameter.setPrice(v);
        fiaciltParameter.setSn(cFillingFacilit.getFacilitSn());
        fiaciltParameter.setKvs(cFillingFacilit.getFaciltKvs());
        fiaciltParameter.setStates(cFillingFacilit.getStatus().toString());
        System.out.println("status:" + cFillingFacilit.getStatus().toString());

        String s = apiService.setFaciltStatus(fiaciltParameter, redisCache.getCacheObject("token:" + "authorizerAccessToken"));
        System.out.println("修改加注机状态返回值:" + s);
        //获取s倒数3,4个字符
        String substring = s.substring(s.length() - 4, s.length() - 2);
        if (substring.equals("成功")) {
            return AjaxResult.success("修改机器状态成功");
        }

        return AjaxResult.error("修改失败,请重试");
    }

    //修改加注机模式
    @ApiOperation("修改加注机模式")
    @GetMapping("/updateStationMode")
    public AjaxResult updateStationMode(@RequestParam(value = "States") Integer States,
                                        @RequestParam(value = "facilitId") Integer facilitId) throws IOException {
        System.out.println(States.toString() + facilitId.toString());

        CFillingFacilit cFillingFacilit = fillingFacilitService.selectCFillingFacilitByFacilitId(facilitId);
        if (cFillingFacilit == null) {
            return AjaxResult.error("加注机不存在");
        }

        String equipmentInfoBySn = apiService.getEquipmentInfoBySn(cFillingFacilit.getFacilitSn(), redisCache.getCacheObject("token:" + "authorizerAccessToken"));
        //解析{"datas":null,"resp_code":1,"resp_msg":"未查询到结果"}
        Map<String, Object> heartbeat = null;
        try {
            String jsonString = equipmentInfoBySn; // 您的 JSON 字符串

            ObjectMapper mapper = new ObjectMapper();

            // 解析 JSON 字符串为 Map
            Map<String, Object> jsonMap = mapper.readValue(jsonString, Map.class);

            // 获取 datas 对象
            Map<String, Object> datas = (Map<String, Object>) jsonMap.get("datas");

            // 获取 manage 对象
            if (datas != null) {
                heartbeat = (Map<String, Object>) datas.get("heartbeat");
            } else {
                return AjaxResult.error("未查询到该设备信息");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("查询加注机状态返回值:" + equipmentInfoBySn);

        //判断加注机是否处于待机状态
        if (!heartbeat.get("equipmentMachineState").toString().equals("1")) {
            return AjaxResult.error("加注机不处于待机状态,无法修改,请重试");
        }
        //调用设备信息修改接口
        FiaciltMode fiaciltMode = new FiaciltMode();
        fiaciltMode.setSn(cFillingFacilit.getFacilitSn());
        fiaciltMode.setStates(States.toString());

        String s = apiService.setFaciltMode(fiaciltMode, redisCache.getCacheObject("token:" + "authorizerAccessToken"));
        System.out.println("修改加注机模式返回值:" + s);
        //获取s倒数3,4个字符
        String substring = s.substring(s.length() - 4, s.length() - 2);
        if (substring.equals("成功")) {
            //修改加注机基本信息
            cFillingFacilit.setFacilitPattern(States);
            fillingFacilitService.updateCFillingFacilit(cFillingFacilit);

            return AjaxResult.success("修改机器模式成功");
        }

        return AjaxResult.error("修改失败,请重试");
    }


}
